<template>
    <div>

        <div class="content" :style="{ bottom: bottomRem }">
            <div class="flex_center_h">
                <div v-for="(item, index) in oagNamesList" :key="index" class="center_item">
                    <span v-if="index == 0" class="font16 color-theme " @click="getUnderOrgUser()">{{ item.name }}</span>
                    <span v-else-if="index == oagNamesList.length - 1" class="font16">>{{ item.name }}</span>
                    <span v-else @click="seleteOrgName(item.name, item.id, index)"
                        class="font16 color-theme">>{{ item.name }}</span>
                </div>
            </div>
            <div v-if="singleSel == 'true' || singleSel == true" class="orgwrap">
                <van-radio-group @change="radioChange" v-model="radioResult">
                    <radio-group :list="treeData"></radio-group>
                </van-radio-group>
            </div>
            <div v-else class="orgwrap">
                <van-checkbox-group @change="checkboxChange" v-model="checkboxResult">
                    <checkbox-group :list="treeData"></checkbox-group>
                </van-checkbox-group>
            </div>

        </div>
        <div ref="btmDiv" class="bottom" style="max-height: 46px;">
            <!-- 单选 -->
            <div v-if="singleSel == 'true' || singleSel == true" class="leftdiv display-ib vertical-a-t">
                <div v-if="JSON.stringify(select) != '{}'">
                    <div @click="deleteSelect(item.id)" class="select font12 display-ib pos-r"
                        style="margin:0 18px 10px 0;">
                        {{ select.name }}
                        <div class="pos-a bg-3 w30" style="right:-8px;top:-6px;">
                            <i class="iconfont icon-del1 font12 color-f"></i>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 多选 -->
            <div v-else class="leftdiv display-ib vertical-a-t" style="overflow-y:auto;height:46px">
                <div v-if="selectList.length > 0">
                    <div v-for="item in selectList" :key="item.name" class="display-ib">
                        <div @click="deleteSelect2(item.id)" class="select font12 display-ib pos-r"
                            style="margin:0 18px 10px 0;">
                            {{ item.name }}
                            <div class="pos-a bg-3 w30" style="right:-8px;top:-6px;">
                                <i class="iconfont icon-del1 font12 color-f"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <van-button @click="confirmSelect" class="qbtn bg-theme color-f font14 fr">确定</van-button>
        </div>

    </div>
</template>

<script>
import { Notify } from 'vant';
import { mapGetters } from 'vuex';
import radioGroup from './radioGroup';
import checkboxGroup from './checkboxGroup';
import { findOneStep } from '@/api/dictapi'
import { Toast } from "vant";

export default {
    computed: {
        ...mapGetters([
            'user'
        ])
    },
    components: {
        radioGroup,
        checkboxGroup
    },
    data() {
        return {
            bottomRem: '', // content距离底部的距离
            singleSel: 'true', // 是单选还是多选
            requSel: 'true', // 是否必须选择
            checkboxResult: [], // 复选框，是个数组
            radioResult: '', // 单选框，暂定为字符串
            orgUserData: [],
            treeData: [],
            select: {}, // 单选-被选中的人
            selectList: [], // 多选-被选中的人
            group: '',
            oagNamesList: [{ id: '', name: '选人' }],
            hadadorgdata: [],
        }
    },
    created() {
        // console.log("由决策项带来的参数",this.params);
    },
    activated() {
        this.params = this.$route.query;
        this.getOrgAndUser();
        this.getBottomH();
    },
    deactivated() {
        this.checkboxResult = []
        this.selectList = [];
    },
    mounted() {
        this.getBottomH();
    },
    methods: {
        getBottomH() {
            let height2 = this.$refs.btmDiv.offsetHeight;
            this.bottomRem = height2 + 'px';
        },
        getOrgAndUser() {
            // console.log('aaaaa'+JSON.stringify(this.params.peopledata))
            if (localStorage.getItem('checkboxResultItem') != '{}' && !!localStorage.getItem('checkboxResultItem')) {
                this.checkboxResult = JSON.parse(localStorage.getItem('checkboxResultItem'))
            }
            if (localStorage.getItem('selectListItem') != '{}' && !!localStorage.getItem('selectListItem')) {
                this.selectList = JSON.parse(localStorage.getItem('selectListItem'))
            }

            let res = this.params.peopledata;
            this.singleSel = res.data[0].singleSel;
            this.requSel = res.data[0].requSel;
            this.group = res.data[0].group;
            if (res.data[0].user.length > 0) {
                this.orgUserData = res.data[0].user;
                var u = res.data[0].user;
                var newO = []; // 组织
                var newO2 = [];
                var newO3 = [];
                var newU = []; // 人
                // console.log('aaaaa'+JSON.stringify(u))
                // u.sort((a, b) => a.treeLevel - b.treeLevel);
                // console.log('bbbb'+JSON.stringify(u))
                for (var i in u) {
                    if (u[i].treeType == 'org') {
                        if (u[i].displayOrder != '1') {
                            newO2.push(u[i]);
                        }
                        if (u[i].treeLevel == 2 || u[i].treeLevel == 3 || u[i].treeLevel == 4 || u[i].treeLevel == 5 || u[i].treeLevel == 6 || u[i].treeLevel == 7) {
                            newO.push(u[i]);
                        }
                    }
                    if (u[i].treeType == 'user') {
                        newU.push(u[i]);
                    }
                }
                console.log(JSON.stringify(newO2), 'newO2222222222222')
                console.log(JSON.stringify(newO), 'newO00000000000')
                //   for (var j in newO2) {
                //   console.log('循环中1222222222')
                //     for (var i in newO) {
                //         if (newO[i].parentId==newO2[j].id){
                //           newO3.push(newO2[j]);
                //           console.log('循环中111111111111111')
                //           break;
                //         }
                //     }
                // }
                for (var j in newO2) {
                    for (var i in newO) {
                        if (newO[i].id != newO2[j].parentId) {
                            if (newO2[j].id == newO[i].parentId) {
                                newO[i].name = newO[i].name + '(' + newO2[j].name + ')';
                                newO3.push(newO[i]);
                            }
                        }
                    }
                }

                console.log(JSON.stringify(newO3), 'newO33333333')
                // var newOO = []; // 有孩子的组织
                // for (var i in newO3) {
                //     newO3[i].hasChild = false;
                //     for (var j in newU) {
                //         if (newU[j].parentId == newO3[i].id) {
                //             newO3[i].hasChild = true; // 这个组织下面有孩子
                //         }
                //     }
                //     if (newO3[i].hasChild == true) {
                //         newOO.push(newO3[i]);
                //     }
                // }
                let newArr = newU.concat(newO3);
                // 只渲染那种组织下面有孩子的
                this.treeData = this.util.toTreeDataDict(
                    newArr,
                    "id",
                    "parentId",
                    "id,name,treeType,parentId"
                );
                var defaultSelectUserList = [];
                defaultSelectUserList = newU.filter(item => item.defaultSelectUser == true)
                console.log("orgUserData:" + JSON.stringify(this.selectList))

                for (var m in defaultSelectUserList) {
                    this.checkboxResult.push(defaultSelectUserList[m].id)
                }

                this.selectList = defaultSelectUserList;
                if (this.selectList.length > 0) {
                    this.selectList[0].group = this.group;
                }
            }

        },
        radioChange(name) {
            console.log('单选选择的人员是' + name);
            for (var i in this.orgUserData) {
                if (this.orgUserData[i].id == name) {
                    this.select = this.orgUserData[i];
                    this.select.group = this.group;
                }
            }
        },
        deleteSelect() {
            this.select = {};
            this.radioResult = '';
        },
        deleteSelect2(name) {
            console.log('1111111111111111111')
            let index = this.selectList.findIndex(item => item.name == name);
            let index2 = this.checkboxResult.findIndex(item => item == name);
            if (index > -1) {
                this.selectList.splice(index, 1);
            }
            if (index2 > -1) {
                this.checkboxResult.splice(index2, 1);
            }

        },
        checkboxChange(names) {
            console.log('选择的人员是' + names);
            this.selectList = this.orgUserData.filter(item => names.includes(item.id));
            if (this.selectList.length > 0) {
                this.selectList[0].group = this.group;
            }
        },
        confirmSelect() {
            if (this.requSel == 'true') { // 是否必须选择
                if (this.singleSel == 'true' || this.singleSel == true) { // 单选
                    if (JSON.stringify(this.select) != '{}') {
                        localStorage.setItem('searchKeyword', JSON.stringify(this.select));
                        localStorage.setItem('searchParams', JSON.stringify(this.params));
                        localStorage.setItem('checkboxResultItem', JSON.stringify(this.checkboxResult));
                        localStorage.setItem('selectListItem', JSON.stringify(this.selectList));
                        this.$router.go(-1);
                        // window.opener = null;
                        // window.open("about:blank", "_top").close()
                    } else {
                        Notify({ type: 'warning', message: '请选择一个联系人' });
                    }
                }
                if (this.singleSel == 'false') { // 多选
                    if (this.selectList.length > 0) {
                        localStorage.setItem('searchKeyword', JSON.stringify(this.selectList));
                        localStorage.setItem('searchParams', JSON.stringify(this.params));
                        localStorage.setItem('checkboxResultItem', JSON.stringify(this.checkboxResult));
                        localStorage.setItem('selectListItem', JSON.stringify(this.selectList));
                        this.$router.go(-1);
                        // window.opener = null;
                        // window.open("about:blank", "_top").close()
                    } else {
                        Notify({ type: 'warning', message: '请至少选择一个联系人' });
                    }
                }
            } else {
                if (this.singleSel == 'true' || this.singleSel == true) { // 单选
                    if (JSON.stringify(this.select) != '{}') {
                        localStorage.setItem('searchKeyword', JSON.stringify(this.select));
                        localStorage.setItem('checkboxResultItem', JSON.stringify(this.checkboxResult));
                        localStorage.setItem('selectListItem', JSON.stringify(this.selectList));
                    } else {
                        Notify({ type: 'warning', message: '未选择办理人！' });
                        return;
                    }
                } else if (this.singleSel == 'false' || this.singleSel == false) {
                    if (this.selectList.length > 0) {

                        localStorage.setItem('searchKeyword', JSON.stringify(this.selectList));
                        localStorage.setItem('checkboxResultItem', JSON.stringify(this.checkboxResult));
                        localStorage.setItem('selectListItem', JSON.stringify(this.selectList));
                    }
                }
                localStorage.setItem('searchParams', JSON.stringify(this.params));
                this.$router.go(-1);
            }

        },
        seleteOrgName(name, id, index) {
            this.oagNamesList = this.oagNamesList.slice(0, index)
            this.findOneStepdata(name, id);
        },
        findOneStepdata(name, id) {
            console.log('传入的参数是' + name + id);
            let obj = this.oagNamesList.find((item) => item.name === name);
            console.log('是否存在' + obj);
            if (obj) {
                console.log('已拥有相同部门' + id);
            } else {
                var org = { id: id, name: name }
                this.oagNamesList.push(org);
            }
            console.log('修改后的部门标题' + JSON.stringify(this.oagNamesList));
            var getOrgdata = {
                userName: this.user.userName,
                orgCode: id,
            };
            Toast.loading({
                message: '提交中',
                forbidClick: true
            });
            findOneStep(getOrgdata).then((res) => {
                Toast.clear()
                if (res.data.data.length > 0) {
                    this.getUnderOrgUser(res.data.data, name, id)
                } else {
                    Notify('此部门下没有符合条件的候选人');
                }
            });
        },
        getUnderOrgUser(data, name, id) {
            let res;
            if (data) {
                res = data;
            } else {
                console.log('直接选择了最前端' + JSON.stringify(this.params.peopledata.data[0].user));
                this.oagNamesList = this.oagNamesList.slice(0, 1)
                res = this.params.peopledata.data[0].user;
            }
            if (res.length > 0) {
                if (data) {
                    if (!this.hadadorgdata.includes(id)) {
                        this.hadadorgdata.push(id);
                        console.log('当前已经有的部门id' + this.hadadorgdata);
                        let newUserData = this.orgUserData.concat(res);;
                        console.log('合并后的总体人员数据' + JSON.stringify(newUserData))
                        this.orgUserData = newUserData
                    }
                }
                var u = res;
                var newO = []; // 组织
                var newO2 = [];
                var newO3 = [];
                var newU = []; // 人
                for (var i in u) {
                    if (u[i].treeType == 'org') {
                        if (u[i].displayOrder != '1') {
                            newO2.push(u[i]);
                        }
                        if (u[i].treeLevel == 2 || (u[i].treeLevel == 3) || (u[i].treeLevel == 4) || (u[i].treeLevel == 5) || (u[i].treeLevel == 6) || (u[i].treeLevel == 7)) {
                            newO.push(u[i]);
                        }
                    }
                    if (u[i].treeType == 'user') {
                        newU.push(u[i]);
                    }
                }
                // for (var j in newO2) {
                //   for (var i in newO) {
                //       if (newO[i].parentId==newO2[j].id){
                //         newO3.push(newO2[j]);
                //         break;
                //       }
                //   }
                // }
                for (var j in newO2) {
                    for (var i in newO) {
                        if (newO[i].id != newO2[j].parentId) {
                            if (newO2[j].id == newO[i].parentId) {
                                newO3.push(newO[i]);
                            }
                        }
                    }
                }
                let newArr = newU.concat(newO3);
                // 只渲染那种组织下面有孩子的
                this.treeData = this.util.toTreeDataDict(
                    newArr,
                    "id",
                    "parentId",
                    "id,name,treeType,parentId"
                );
            }
        },
    }
}
</script>

<style scoped>
.content {
    position: absolute;
    top: 50px;
    right: 0;
    left: 0;
    /* background: red; */
    overflow-y: auto;
}

.orgwrap {
    width: 100%;
}

.bottom {
    position: fixed;
    right: 0;
    bottom: 0;
    left: 0;
    min-height: 46px;
    background: #eee;
}

.leftdiv {
    width: calc(100% - 90px);
    padding: 0px 10px 10px 10px;
    min-height: 46px;

}

.qbtn {
    width: 80px;
    height: 38px;
    line-height: 38px;
    margin: 4px 5px;
    border-radius: 5px;
}

.select {
    padding: 4px 7px;
    border: 1px solid #0080cb;
    background: #e9f7ff;
    border-radius: 4px;
    color: #0080cb;
}

.w30 {
    width: 16px;
    height: 16px;
    background: #333;
    border-radius: 50%;
    text-align: center;
    line-height: 16px;
}
</style>
<style>
.van-button__content {
    font-size: unset;
}
</style>
